package com.dhcc.bpm.modules.auth.utils;

import com.dhcc.bpm.modules.system.entity.Role;
import com.dhcc.bpm.modules.system.entity.User;
import com.dhcc.bpm.modules.system.entity.UserInfo;
import com.dhcc.bpm.modules.system.mapper.DeptMapper;
import com.dhcc.bpm.modules.system.vo.DeptVO2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.secure.TokenInfo;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName TokenUtil
 * @Description 认证工具类
 * @Author xiafayu
 * @Date 2020/2/21 0021 15:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 **/
public class TokenUtil {
	private static final Logger log = LoggerFactory.getLogger(TokenUtil.class);
	@Autowired
	private DeptMapper deptMapper;
	public final static String TENANT_HEADER_KEY = "Tenant-Id";
	public final static String DEFAULT_TENANT_ID = "000000";
	public final static String USER_TYPE_HEADER_KEY = "User-Type";
	public final static String DEFAULT_USER_TYPE = "web";
	public final static String USER_NOT_FOUND = "用户名或密码错误";
	public final static String HEADER_KEY = "Authorization";
	public final static String CAPTCHA_HEADER_KEY = "Captcha-key";
	public final static String GRANT_TYPE = "captcha";
	public final static String CAPTCHA_ERROR_CODE = "C403";
	public final static String HEADER_PREFIX = "Basic ";
	public final static String DEFAULT_AVATAR = "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";

	/**
	 * @Description 创建认证token
	 * @Author xiafayu
	 * @Date 2020/2/24 17:42
	 * @param userInfo 用户信息
	 * @param role
	 * @return org.springblade.core.tool.support.Kv
	 **/
	public static Kv createAuthInfo(UserInfo userInfo, Role role) {
		Kv authInfo = Kv.create();
		User user = userInfo.getUser();
        List<DeptVO2> depts = userInfo.getDepts();
        user.setRoleId(Func.toStr(role.getId()));
		//设置jwt参数
		Map<String, String> param = new HashMap<>(16);
		List<String> roleName = new ArrayList<String>();
		roleName.add(role.getRoleAlias());
		param.put(TokenConstant.TOKEN_TYPE, TokenConstant.ACCESS_TOKEN);
		param.put(TokenConstant.TENANT_ID, user.getTenantId());
		param.put(TokenConstant.USER_ID, Func.toStr(user.getId()));
		param.put(TokenConstant.DEPT_ID, user.getDeptId());
		param.put(TokenConstant.ROLE_ID, Func.toStr(role.getId()));
		param.put(TokenConstant.ACCOUNT, user.getAccount());
		param.put(TokenConstant.USER_NAME, user.getAccount());
		param.put(TokenConstant.NICK_NAME, user.getRealName());
		param.put(TokenConstant.ROLE_NAME, Func.join(roleName));
		//拼装accessToken
		try {
			TokenInfo accessToken = AuthUtil.createJWT(param, "audience", "issuser", TokenConstant.ACCESS_TOKEN);

			//返回accessToken
			return authInfo.set(TokenConstant.TENANT_ID, user.getTenantId())
				.set(TokenConstant.ACCOUNT, user.getAccount())
				.set(TokenConstant.USER_NAME, user.getAccount())
				.set(TokenConstant.NICK_NAME, user.getRealName())
				.set("role_alias", Func.join(roleName))
				.set(TokenConstant.ROLE_NAME, role.getRoleName())
				.set(TokenConstant.AVATAR, Func.toStr(user.getAvatar(), TokenConstant.DEFAULT_AVATAR))
				.set(TokenConstant.ACCESS_TOKEN, accessToken.getToken())
				.set(TokenConstant.REFRESH_TOKEN, createRefreshToken(userInfo).getToken())
				.set(TokenConstant.TOKEN_TYPE, TokenConstant.BEARER)
				.set(TokenConstant.EXPIRES_IN, accessToken.getExpire())
				.set(TokenConstant.LICENSE, TokenConstant.LICENSE_NAME)
					.set("dept", depts )
					.set("deptAll", userInfo.getDeptAll() )
				.set("user", user);
		} catch (Exception ex) {
			log.error("生成token异常：{}", ex);
			return authInfo.set("error_code", HttpServletResponse.SC_UNAUTHORIZED).set("error_description", ex.getMessage());
		}
	}

	/**
	 * @Description 创建refreshToken
	 * @Author xiafayu
	 * @Date 2020/2/24 17:42
	 * @param userInfo 用户信息
	 * @return org.springblade.core.secure.TokenInfo
	 **/
	private static TokenInfo createRefreshToken(UserInfo userInfo) {
		User user = userInfo.getUser();
		Map<String, String> param = new HashMap<>(16);
		param.put(TokenConstant.TOKEN_TYPE, TokenConstant.REFRESH_TOKEN);
		param.put(TokenConstant.USER_ID, Func.toStr(user.getId()));
		return AuthUtil.createJWT(param, "audience", "issuser", TokenConstant.REFRESH_TOKEN);
	}

}
